package top.itaso.app.ui.wifi;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.permissionx.guolindev.PermissionX;
import com.permissionx.guolindev.callback.RequestCallback;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import top.itaso.lib.widget.helper.UniversalItemDecoration;
import top.itaso.app.databinding.FragmentWifiScanBinding;
import top.itaso.app.room.entity.WifiScanResultEntity;
import top.itaso.lib.alog.ALog;
import top.itaso.lib.common.ToastUtils;


public class WifiScanFragment extends Fragment {

    private WifiScanResultViewModel mViewModel;
    private FragmentWifiScanBinding binding;

    private WifiManager mWifiManager;
    private WifiStateBroadcastReceiver mWifiStateBroadcastReceiver;

    private TextView mTvWifiScan;

    private WifiScanResultAdapter mWifiScanResultAdapter;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mViewModel = new ViewModelProvider(this).get(WifiScanResultViewModel.class);

        mViewModel.getWifiScanResults().observe(getViewLifecycleOwner(), new Observer<List<WifiScanResultEntity>>() {
            @Override
            public void onChanged(List<WifiScanResultEntity> wifiScanResultEntities) {
                ToastUtils.getInstance().showShortToast(requireContext(), "当前录入Wifi数=" + wifiScanResultEntities.size());
            }
        });

        binding = FragmentWifiScanBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        mTvWifiScan = binding.tvWifiScan;
        mTvWifiScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    ToastUtils.getInstance().showShortToast(requireContext(), "扫描Wifi需要打开定位权限");
                    return;
                }
                mWifiManager.startScan();
                mTvWifiScan.setText("附近Wifi搜索中，请稍后......");
                mTvWifiScan.setEnabled(false);
            }
        });

        RecyclerView wifiScanResultList = binding.rvWifiList;
        wifiScanResultList.setLayoutManager(new LinearLayoutManager(requireContext()));
        wifiScanResultList.addItemDecoration(itemDecoration);
        mWifiScanResultAdapter = new WifiScanResultAdapter();
        wifiScanResultList.setAdapter(mWifiScanResultAdapter);

        return root;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mWifiManager = (WifiManager) requireContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        if (!mWifiManager.isWifiEnabled()) {
            mTvWifiScan.setEnabled(false);
            ToastUtils.getInstance().showShortToast(requireContext(), "小可爱，您需要先打开Wifi哦~~~");
        }

        PermissionX.init(this)
                .permissions(Manifest.permission.ACCESS_FINE_LOCATION)//, Manifest.permission.CHANGE_WIFI_STATE
                .request(new RequestCallback() {
                    @Override
                    public void onResult(boolean allGranted, List<String> grantedList, List<String> deniedList) {
                        if (!allGranted) {
                            mTvWifiScan.setEnabled(false);
                            ToastUtils.getInstance().showShortToast(requireContext(), "您还需要打开Wifi后才可以使用");
                            return;
                        }
                        if (!mWifiManager.isWifiEnabled()) {
                            mTvWifiScan.setEnabled(false);
//                            ToastUtils.getInstance().showShortToast(requireContext(), "您还没打开Wifi哦");
                        } else {
                            mTvWifiScan.setEnabled(true);
                        }
                    }
                });


    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        registerWifiReceiver(context);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        if (mWifiStateBroadcastReceiver != null) {
            requireContext().unregisterReceiver(mWifiStateBroadcastReceiver);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    private void registerWifiReceiver(Context context) {
        mWifiStateBroadcastReceiver = new WifiStateBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        //监听wifi是开关变化的状态:WIFI_STATE_CHANGED_ACTION 关心wifi硬件本身打开与关闭，不关心wifi是否连接
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);//监听wifi列表变化（开启一个热点或者关闭一个热点）
        context.registerReceiver(mWifiStateBroadcastReceiver, filter);
    }


    private UniversalItemDecoration itemDecoration = new UniversalItemDecoration() {
        @Override
        public Decoration getItemOffsets(int position) {
//                if (position >= viewModel.cases.getValue().size() - 1) {//控制最后一个Item是否需要有分割线
//                    return null;
//                }
            ColorDecoration decoration = new ColorDecoration();
            decoration.bottom = 2;
            decoration.top = 2;
            decoration.left = 5;
            decoration.right = 5;
            decoration.decorationColor = Color.TRANSPARENT;
//                decoration.decorationColor = Color.GRAY
            return decoration;
        }
    };


    //监听wifi状态
    public class WifiStateBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            ALog.d("action:%s,intent:%s", action, intent);
            if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {//监听wifi列表变化（开启一个热点或者关闭一个热点
                mTvWifiScan.setText("扫描附件的Wifi");
                mTvWifiScan.setEnabled(true);
                //TODO 可使用 getScanResults() 获取扫描结果
                ArrayList<ScanResult> scanWifiList = (ArrayList<ScanResult>) mWifiManager.getScanResults();
                Iterator<ScanResult> it = scanWifiList.iterator();
                while (it.hasNext()) {
                    ScanResult scanResult = it.next();
                    if (TextUtils.isEmpty(scanResult.SSID)) {
                        it.remove();
                    }
                }
                mWifiScanResultAdapter.refreshWifiData(scanWifiList);
                mViewModel.saveWifiScanResult(scanWifiList);
//                for (ScanResult scanResult : scanWifiList) {
//                    ALog.d("scanResult=%s,BSSID:%s", scanResult.SSID, scanResult.BSSID);
//                }
            } else if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {//wifi状态变化:WIFI_STATE_CHANGED_ACTION 关心wifi硬件本身打开与关闭，不关心wifi是否连接
                int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_DISABLED);//当前wifi状态
                int previousWifiState = intent.getIntExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, WifiManager.WIFI_STATE_DISABLED);//wifiState之前的状态
                ALog.d("previousWifiState:%s,wifiState:%s", previousWifiState, wifiState);
                if (wifiState == 0 && previousWifiState == 3) {
                    mTvWifiScan.setEnabled(false);
                    mTvWifiScan.setText("Wifi关闭中");
                } else if (wifiState == 2 && previousWifiState == 1) {
                    mTvWifiScan.setEnabled(false);
                    mTvWifiScan.setText("Wifi打开中，请稍等......");
                } else if (wifiState == 3) {
                    mTvWifiScan.setEnabled(true);
                    mTvWifiScan.setText("扫描附近的Wifi");
                } else {
                    mTvWifiScan.setEnabled(false);
                    mTvWifiScan.setText("当前Wifi不可用");
                }
            }
        }
    }
}